package com.hunlian.makelove.activity;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.hunlian.makelove.R;
import com.hunlian.makelove.TakeCameraOrAlbum;
import com.hunlian.makelove.view.CropImageView;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class CropperActivity extends BaseActivity{

	private CropperActivity mSelf;
	private Button mBtnCrop,mBtnRotate;
	private CropImageView mCropImageView;
	private int[] mDegreeArray = {0,90,180,270,360};
	private int mDegreeId = 0;
	private LinearLayout mScreenshotLayout;
	private String mPicPath;
	private TakeCameraOrAlbum mTakeCameraOrAlbum;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mSelf = this;
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.cropper_activity);
		mPicPath = getIntent().getStringExtra("path");
				
		mTakeCameraOrAlbum = new TakeCameraOrAlbum();
		
/*		ImageButton mIbBack = (ImageButton) findViewById(R.id.back);
		mIbBack.setVisibility(View.GONE);
		
		Button rightBtn = (Button) findViewById(R.id.btn_nav_right);
		rightBtn.setVisibility(View.GONE);

		
		TextView mTvTitle = (TextView) findViewById(R.id.title);
		mTvTitle.setText("裁剪图片");*/
		
		mCropImageView = (CropImageView) findViewById(R.id.CropImageView);
		mBtnRotate = (Button) findViewById(R.id.Button_rotate);
		mBtnCrop = (Button) findViewById(R.id.Button_crop);
		mScreenshotLayout = (LinearLayout) findViewById(R.id.ll_pic);
		
/*		Bitmap bmp = BitmapFactory.decodeFile(mPicPath);
		mCropImageView.setImageDrawable(mTakeCameraOrAlbum.bitmapToDrawable(bmp));*/
		mTakeCameraOrAlbum.loadPic(mSelf,mCropImageView,mPicPath);
		
        // Initialize the Crop button.
		mBtnCrop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            	
            	
                //final Bitmap croppedImage = mCropImageView.getCroppedImage();
                //mCropImageView.setImageBitmap(croppedImage);
                boolean boo = saveWateredPhoto(); 
                if(boo==false){
                	Toast.makeText(mSelf, "裁剪的图片尺寸太小，请重新选图", 0).show();
                	return;
                }
                setResult(RESULT_OK);
                finish();
            }
        });
		
		mBtnRotate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 创建新的图片
				Bitmap resizedBitmap;
				try {
					//加载需要操作的图片，这里是一张图片
					Bitmap bitmapOrg = BitmapFactory.decodeFile(mPicPath);
					//Bitmap bitmapOrg = BitmapFactory.decodeResource(getResources(),R.drawable.img_calendar_guide);
					
					//获取这个图片的宽和高
					int width = bitmapOrg.getWidth();
					int height = bitmapOrg.getHeight();
					
					// 创建操作图片用的matrix对象
					Matrix matrix = new Matrix();
					
					mDegreeId = mDegreeId+1;
					if(mDegreeId==4){
						mDegreeId = 0;
					}
					
					//旋转图片 动作
					matrix.postRotate(mDegreeArray[mDegreeId]);
					
					resizedBitmap = Bitmap.createBitmap(bitmapOrg, 0, 0,
					width, height, matrix, true);
					
					mCropImageView.setImageBitmap(resizedBitmap);
				} catch (Exception e) {
					e.printStackTrace();
				}
                
                
            }
        });
		
	}

    /**截取包含水印的照片*/
    private boolean saveWateredPhoto() {
    	
    	float[] edgeArray = mCropImageView.getEdgeArray();
/*        System.out.println("X: "+edgeArray[0]);
        System.out.println("Y: "+edgeArray[1]);
        System.out.println("Right: "+edgeArray[2]);
        System.out.println("Bottom: "+edgeArray[3]);*/
        
    	float borderWidth = mCropImageView.getBorderWidth();
        
        View view = getWindow().getDecorView();  
        view.setDrawingCacheEnabled(true);  
        view.buildDrawingCache();  
        Bitmap bitmap = view.getDrawingCache(); 
        
        Rect frame = new Rect();  
        getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);  
        int toHeight = frame.top; 
        //System.out.println("frame.top :"+toHeight);
        float width = (int)(edgeArray[2]-(int)edgeArray[0]-borderWidth*2);
        float height = (int)(edgeArray[3]-(int)edgeArray[1]-borderWidth*2);
        if(width<=0 || height <=0){
        	//图片尺寸太小
        	return false;
        }
        
        Bitmap bmp = Bitmap.createBitmap(bitmap, (int)(edgeArray[0]+borderWidth),(int)(edgeArray[1]+toHeight+borderWidth), 
        		(int)(edgeArray[2]-(int)edgeArray[0]-borderWidth*2), (int)(edgeArray[3]-(int)edgeArray[1]-borderWidth*2)); 
		
		mCropImageView.setImageBitmap(bmp);
		saveBitmap(mPicPath,bmp);
		
		return true;
    }
    
	/** 保存方法 */
	  public void saveBitmap(String picName,Bitmap bm) {
/*	   String path = Environment.getExternalStorageDirectory().getPath();  
	   File f = new File(path, picName);*/
	   File f = new File(picName);
	   if (f.exists()) {
	    f.delete();
	   }
	   try {
	    FileOutputStream out = new FileOutputStream(f);
	    bm.compress(Bitmap.CompressFormat.PNG, 100, out);
	    out.flush();
	    out.close();
	   } catch (FileNotFoundException e) {
	    e.printStackTrace();
	   } catch (IOException e) {
	    e.printStackTrace();
	   }
	 
	 }
}
